package com.maltys.sign_aspect.util;

import com.maltys.sign_aspect.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author luonankun
 * @date 2022/10/21
 **/
@Slf4j
public class ClientSignStrategy extends SignStrategyAdapter {
    /**
     * 请求接口验签
     *
     * @param request
     * @param signKey
     * @param appKeyIdx
     * @return
     */
    @Override
    public Boolean checkSign(HttpServletRequest request, String signKey, int[][] appKeyIdx) throws Exception {
        String requestSign = getRequestSign(request);
        if (StringUtils.isEmpty(requestSign)) {
            log.info("#ServerSignStrategy.checkSign, sign miss!!!");
            throw new Exception(ErrorCode.APP_SIGNATURE_ERROR.getMsg());
        }
        Map<String, Object> paramsMap = this.getRequestParams(request);

//        String signSrc = ParametersInclude.concatParamsSingleValue(paramsMap);
//        return ParametersInclude.checkSignSdk(signKey,signSrc,requestSign);
        return null;
    }

    @Override
    protected Map<String, Object> getRequestParams(HttpServletRequest request) throws Exception {
        Map<String, Object> requestParams = super.getRequestParams(request);

        Object timeStamp = requestParams.get(TIMESTAMP);
        if (timeStamp == null) {
            log.warn("#ServerSignStrategy.checkSign, timestamp miss!!!");
            throw new Exception(ErrorCode.APP_SIGNATURE_ERROR.getMsg());
        }
        long timeStampValue = Long.parseLong(String.valueOf(timeStamp));
        int timeOutMillis = 5 * 60 * 1000;
        if (System.currentTimeMillis() - timeStampValue > timeOutMillis) {
            log.warn("#ServerSignStrategy.checkSign, timestamp timeout!!!");
            throw new Exception(ErrorCode.APP_SIGNATURE_ERROR.getMsg());
        }
        return requestParams;
    }
}
